package com.yanqu.road.dao.impl.activity.suoyao;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.activity.suoyao.SuoYaoBoxData;

import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;

public class SuoYaoBoxDataDaoImpl extends TempDataObjectDao<SuoYaoBoxData> {

    public static String getSuoYaoBoxDataSql = "select * from t_c_activity_suoyao_box_data where activityId=?";

    public SuoYaoBoxData getSuoYaoBoxData(int activityId) {
        ResultSet rs = null;
        CallableStatement call = null;
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(getSuoYaoBoxDataSql);
            int i = 1;
            call.setInt(i++, activityId);
            rs = call.executeQuery();
            if (rs.next()) {
                return parse(rs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return null;
    }

    public static String updateSuoYaoBoxDataSql = "update t_c_activity_suoyao_box_data set count=? where activityId=?";

    @Override
    protected boolean updateData(SuoYaoBoxData suoYaoBoxData) {
        suoYaoBoxData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCross2Db());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, suoYaoBoxData.getCount()));
        para.put(i++, new DbParameter(Types.INTEGER, suoYaoBoxData.getActivityId()));
        if (getDb().executeNoneQuery(updateSuoYaoBoxDataSql, para) > 0) {
            return true;
        }
        return false;
    }

    public static String insertSuoYaoBoxDataSql = "insert into t_c_activity_suoyao_box_data(activityId,count) values (?,?)";

    @Override
    protected boolean addData(SuoYaoBoxData suoYaoBoxData) {
        suoYaoBoxData.setBeginWriteTime();
        getDb().setConnName(DbNameStrategy.getCross2Db());
        int i = 1;
        Map<Integer, DbParameter> para = new HashMap<Integer, DbParameter>();
        para.put(i++, new DbParameter(Types.INTEGER, suoYaoBoxData.getActivityId()));
        para.put(i++, new DbParameter(Types.INTEGER, suoYaoBoxData.getCount()));
        if (getDb().executeNoneQuery(insertSuoYaoBoxDataSql, para) > 0) {
            return true;
        }
        return false;

    }

    @Override
    protected SuoYaoBoxData parseData(ResultSet rs) throws SQLException {
        SuoYaoBoxData suoYaoBoxData = new SuoYaoBoxData();
        suoYaoBoxData.setActivityId(rs.getInt("activityId"));
        suoYaoBoxData.setCount(rs.getInt("count"));
        return suoYaoBoxData;
    }

}
